"""
Author: Meng
Date: 2018/11/5
"""
from app.models.square.topic import Topics, TopicFileShip, TopicTags, TopicTagsShip
from app.models.admin.user import User
from flask_restful import Resource, reqparse, fields
from app.api import api
from f_lib.principal.auth import auth_token
from f_lib.code import Msg
from flask import g, make_response, Response, request
import os
from settings import THUMB_IMG
from f_lib.marshal_list import marshal


class CreateTopic(Resource):
    parse = reqparse.RequestParser()
    parse.add_argument('title', required=True, type=str)
    parse.add_argument('content', type=str)
    parse.add_argument('file', type=dict, action='append')
    parse.add_argument('tags', type=str, action='append')

    @auth_token()
    def post(self):
        arg = self.parse.parse_args()
        title = arg['title']
        if title:
            content = arg.get('content')
            topic = Topics.create(title=title, content=content, user_id=g.user.id, name=g.user.name)
            file = arg.get('file')
            if file:
                for fi in file:
                    ext = os.path.splitext(fi.get('filename'))[-1]
                    f = TopicFileShip(topic.id, **fi)
                    if ext:
                        if ext in THUMB_IMG:
                            f.is_img = 1
                    f.save()

            tags = arg.get('tags')
            if tags:
                for tag in tags:
                    ta = TopicTags.query_one(tag_name=tag)
                    if not ta:
                        ta = TopicTags(tag, from_uid=g.user.id)
                        ta.save()
                    else:
                        count = ta.like if ta.like else 0
                        ta.update(like=count + 1)
                    TopicTagsShip.create(topic_id=topic.id, tag_id=ta.id)

            return Msg.success(topic_id=topic.id)
        else:
            return Msg.failed('标题必填')


class ListTopics(Resource):
    parse = reqparse.RequestParser()
    parse.add_argument('pn', type=int, default=10)
    parse.add_argument('page', type=int, default=1)
    parse.add_argument('tag', type=str)
    parse.add_argument('type', type=str, choices=('me', 'all'))

    def get(self):
        arg = self.parse.parse_args()
        page = arg.get('page', 1)
        pn = arg.get('pn', 10)
        if pn > 100:
            pn = 100
        tag = arg.get('tag')
        where_type = arg.get('type')

        params = dict(
            id=None,
            user_id=None,
            name=None,
            title=None,
            like=None,
            ctime=None
        )
        where = ["is_show=1"]
        if where_type == 'me':
            user = User.verify_auth_token(request.cookies.get('assess_key'))
            where.append('user_id={}'.format(user.id))
        topics = Topics.query_where_many(params=list(params.keys()), wheres=where, limit=[(page - 1) * pn, pn])
        tcount = Topics.query_where_many_count(where)
        ts = marshal(params, topics)
        return Msg.success(topics=ts, total=tcount)


class TopicDetail(Resource):
    parse = reqparse.RequestParser()
    parse.add_argument('id', required=True, type=int)
    file_field = {'id': None,
                  'filename': None,
                  'name': None,
                  'is_img': None,
                  }
    tag_field = {
        'id': None,
        'tag_name': None,
        'like': None
    }
    topic_field = {
        'id': None,
        'user_id': None,
        'title': None,
        'content': None,
        'name': None,
        'like': None,
        'ctime': None,
        'utime': None
    }

    def post(self):
        arg = self.parse.parse_args()
        topic = Topics.query_one(**arg)
        if topic:
            m_topic = marshal(self.topic_field, topic)
            m_tags = []
            m_files = []
            files = TopicFileShip.query_many(topic_id=topic.id)
            if files:
                m_files = marshal(self.file_field, files)

            tags_ship = TopicTagsShip.query_many(topic_id=topic.id)
            if tags_ship:

                for tag_s in tags_ship:
                    tag = TopicTags.query_one(id=tag_s.tag_id)
                    if tag:
                        m_tags.append(marshal(self.tag_field, tag).copy())

            return Msg.success(topic=m_topic, files=m_files, tags=m_tags)
        return Msg.failed_dict(1002)


class LikeTopic(Resource):
    parse = reqparse.RequestParser()
    parse.add_argument('id', type=int, required=True)

    @auth_token()
    def post(self):
        arg = self.parse.parse_args()
        topic = Topics.query_one(**arg)
        if topic:
            count = topic.like if topic.like else 0
            topic.update(like=count + 1)
        return Msg.success('点赞成功！')


class DelTopic(Resource):
    parse = reqparse.RequestParser()
    parse.add_argument('id', type=int, required=True)

    @auth_token()
    def post(self):
        arg = self.parse.parse_args()
        topic = Topics.get_by_id(arg['id'])
        if topic:
            if topic.user_id == g.user.id:
                topic.delete()
                return Msg.success()
            else:
                return Msg.failed_dict(7001)
        return Msg.failed_dict(1002)


api.add_resource(CreateTopic, '/topic/add', endpoint='add_topic')
api.add_resource(DelTopic, '/topic/del', endpoint='del_topic')
api.add_resource(ListTopics, '/topic/list', endpoint='topic_list')
api.add_resource(TopicDetail, '/topic/detail', endpoint='topic_detail')
api.add_resource(LikeTopic, '/topic/like', endpoint='like_topic')
